var map;

// Creating a walk - Global
var points = new Array();
var descrs = new Array();
var photos = new Array();
var marker;

var walk;
var count = 0;

// Marker
var redIcon = new GIcon();
redIcon.image = "mapImages/redSquare.png";
redIcon.iconSize = new GSize(8, 8);
redIcon.iconAnchor = new GPoint(4, 4);
redIcon.infoWindowAnchor = new GPoint(4, 4);

// Geocoder for reverse geocoding
var geocode;

var walkWeather;
var walkLocation;
var walkSlope;


function init() 
{
	if (GBrowserIsCompatible()) 
	{
		// Setup the Map
		map = new GMap2(document.getElementById("divMap"));
		map.addControl(new GLargeMapControl());
		map.enableScrollWheelZoom();
		map.addMapType(G_PHYSICAL_MAP);
    map.setCenter(new GLatLng(44.976436, -93.232242), 15);
    
    // Initialize geocoder
    geocode = new GClientGeocoder();
    
    // Load existing walks as watermark!
    
    // Disable Save
    document.getElementById('btnSave').className = "btnOff";
    document.getElementById('btnSave').disabled = true;
  }//GBrowser
  else
  {
    alert('You are using incompatible browser!! Use Google Chrome or Mozilla Firefox!');
  }
  
  // Mouse Click Event on the map
  GEvent.addListener(map, "click", function(overlay, latlng) 
  {
    if(!overlay)
    {
      // Close infowindow just in case!
      map.closeInfoWindow();
      
      // Add the current click to the points array
      points[count] = latlng;
      
      // Add the marker to the map
      marker = createMarker(latlng, count);
      map.addOverlay(marker);
      
      // Initialize descrs and photos
      descrs[count] = '';
      photos[count] = '';
      
      // Increment the number of points in the walk
      count++;
      
      // Initialize the walk
      if(count == 2 )
      {
        // If it is the second point create a polyline and add it to the map
        walk = new GPolyline(points, "#ff0000", 4);
        map.addOverlay(walk);
        
        // Click listener for walk
        GEvent.addListener(walk, "click", function(latlng) 
        {
          alert('Can be used to insert a new vertex in the middle of the line.. for now it is out of scope.. Clicked at lat : ' + latlng.lat() + ', long : ' + latlng.lng());
        });
        
        // Enable Save Button
        document.getElementById('btnSave').className = "btn";
        document.getElementById('btnSave').disabled = false;
      }
      else if( count > 1 )
      {
        // More than two points insert the point into the polyline
        walk.insertVertex(count - 1, points[count-1]);
      }
    }
  });// On click Listener
}//init

//Function to create a marker with the html description
function createMarker(latlng, idx) 
{
  var marker = new GMarker(latlng, {icon:redIcon,draggable:false});
  var tabs = [];
  
  // Description
  var html = '<div class="createInfoWindow"><input type="hidden" id="idx" value="' + idx + '"/>' + 
             '<b>Enter details</b><br/>' +
             '<textarea id="desc" class="textarea" style="margin-left:35px" onChange="descChange(document.getElementById(\'idx\').value);" rows=10 cols=10></textarea><br/>' +
             '<b>Enter photo link</b><br/>' +
             '<input type="text" id="photo" class="walkName" style="margin-left:35px" onChange="photoChange(document.getElementById(\'idx\').value);" />' +
             '</div>';

  // Marker on click event  
  GEvent.addListener(marker, 'click', function() 
  {
    var infoWindow = map.getInfoWindow();
    marker.openInfoWindowHtml(html,{noCloseOnClick:true,onOpenFn:function(){infoWindow.reset(this.getPoint(),infoWindow.getTabs(),new GSize(500,500),null,null);
	}});
  });
 
  return marker;
}//createMarker

function descChange(idx)
{
  descrs[idx] = document.getElementById('desc').value;
}

function photoChange(idx)
{
  photos[idx] = document.getElementById('photo').value;
}

function saveWalk()
{
  // Check total number of points before save
  if(count > 1)
  {
    geocode.getLocations(points[0], function(response)
    {
      // Prepare the variables
      var arguments = "?";
      // title
      arguments += "title=" + document.getElementById('walkName').value;
      
      // uid
      arguments += "&uid=" + document.getElementById('uid').value;
      
      // walkDesc
      arguments += "&walkDesc=" + document.getElementById('walkDesc').value;
      
      // pntCnt
      arguments += "&pntCnt=" + count;
      
      // center
      arguments += "&center=" + walk.getBounds().getCenter().lat() + ',' + walk.getBounds().getCenter().lng();

      // pnts
      arguments += "&pnts=" + points[0].lat() + "," + points[0].lng();
      for(var i=1; i<count; i++)
        arguments += "," + points[i].lat() + "," + points[i].lng();
        
      // bounds
      //arguemnts += "&bounds=" + bounds;

      // desc
      arguments += "&desc=" + descrs[0];
      for(var i=1; i<count; i++)
        arguments += "," + descrs[i];
      
      // photo
      arguments += "&photo=" + photos[0];
      for(var i=1; i<count; i++)
        arguments += "," + photos[i];
        
      // rtng
      arguments += "&rtng=0";
      
      // rtngCnt
      arguments += "&rtngCnt=0";
      
      // views
      arguments += "&views=0";
      
      // favs
      arguments += "&favs=0";
      
      // zip
      var zip = -1;
      if(response.Status.code == 200)
      {
        if(response.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber != null)
          zip = response.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
        else if(response.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber != null)
          zip = response.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber; 
      }
      arguments += "&zip=" + zip;
      
      // place
      var place = '';
      if(response.Status.code == 200)
      {
        if(response.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName != null)
          place = response.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
        else if(response.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.LocalityName != null)
          place = response.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.LocalityName; 
      }
      arguments += "&place=" + place;
      
      // place
      var state = '';
      if(response.Status.code == 200)
      {
        if(response.Placemark[0].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName != null)
          state = response.Placemark[0].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName; 
        else if(response.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName != null)
          state = response.Placemark[0].AddressDetails.Country.AdministrativeArea.AdministrativeAreaNameSubAdministrativeArea.SubAdministrativeAreaName;
      }
      arguments += "&state=" + state;
      
      // weather
      arguments += "&weather=0";
      
      // location
      arguments += "&location=0";
      
      // slope
      arguments += "&slope=0";
      
      // Save it to file
      GDownloadUrl('mapCreateWalk.php' + arguments, function(data, responseCode) 
      {
        //Do something with the data
        if(responseCode == 200)
        {
          if(parseInt(data) >= 1)
          {
            count = 0;
            points = [];
            document.getElementById('btnSave').disabled = true;
            alert("Save Successful!");
            window.location =  "walks.php?id="+data;
            // Redirect
          }
          else
            alert("Error Saving Data! Error Code : " + data); 
        }
        else
          alert("Save Failed! Please Retry!");
      }); //Storing Value.. AJAX Call!!
    });
  }
  else
    alert("Please create a walk!!");
}

function weatherSelect(tagName)
{
	if(tagName =="sun")
	{
		walkWeather = 0;
		document.getElementById('sunSafe').src = "images/tagSun.png";
		document.getElementById('rainSafe').src = "images/tagRain2.png";
		document.getElementById('snowSafe').src = "images/tagSnow2.png";
	}	
	if(tagName =="rain")
	{
		walkWeather = 2;
		document.getElementById('sunSafe').src = "images/tagSun2.png";
		document.getElementById('rainSafe').src = "images/tagRain.png";
		document.getElementById('snowSafe').src = "images/tagSnow2.png";
	}
	if(tagName =="snow")
	{
		walkWeather = 1;
		document.getElementById('sunSafe').src = "images/tagSun2.png";
		document.getElementById('rainSafe').src = "images/tagRain2.png";
		document.getElementById('snowSafe').src = "images/tagSnow.png";
	}
}

function locationSelect(tagName)
{
	if(tagName =="city")
	{
		walkLocation = 0;
		document.getElementById('city').src = "images/tagCity.png";
		document.getElementById('subUrban').src = "images/tagSubUrban2.png";
		document.getElementById('scenic').src = "images/tagScenic2.png";
	}	
	if(tagName =="subUrban")
	{
		walkLocation = 1;
		document.getElementById('city').src = "images/tagCity2.png";
		document.getElementById('subUrban').src = "images/tagSubUrban.png";
		document.getElementById('scenic').src = "images/tagScenic2.png";
	}
	if(tagName =="scenic")
	{
		walkLocation = 2;
		document.getElementById('city').src = "images/tagCity2.png";
		document.getElementById('subUrban').src = "images/tagSubUrban2.png";
		document.getElementById('scenic').src = "images/tagScenic.png";
	}
}

function terrainSelect(tagName)
{
	if(tagName =="plains")
	{
		walkWeather = 0;
		document.getElementById('plains').src = "images/tagPlain.png";
		document.getElementById('gentleSlope').src = "images/tagGentle2.png";
		document.getElementById('rugged').src = "images/tagRugged2.png";
	}	
	if(tagName =="gentleSlope")
	{
		walkWeather = 1;
		document.getElementById('plains').src = "images/tagPlain2.png";
		document.getElementById('gentleSlope').src = "images/tagGentle.png";
		document.getElementById('rugged').src = "images/tagRugged2.png";
	}
	if(tagName =="rugged")
	{
		walkWeather = 2;
		document.getElementById('plains').src = "images/tagPlain2.png";
		document.getElementById('gentleSlope').src = "images/tagGentle2.png";
		document.getElementById('rugged').src = "images/tagRugged.png";
	}		
}

window.onload = init
window.onunload = GUnload
